#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>

#define BUF_SIZE 128
#define THREADS 20

// 不指定属性的互斥量可以用 PTHREAD_MUTEX_INITIALIZER 创建
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

// open a file, increment the content of the file
static void* inc(void* p) {
    char* filename = p;

    FILE* fp = fopen(filename, "r+");
    char buf[BUF_SIZE];

    // read is not allowed concurrently
    pthread_mutex_lock(&mtx);
    fgets(buf, BUF_SIZE, fp);
    int i = atoi(buf);
    fseek(fp, 0, SEEK_SET);
    fprintf(fp, "%d\n", i+1);
    fclose(fp);
    pthread_mutex_unlock(&mtx);


    pthread_exit(NULL);
    // 在这里释放互斥量
}

int main(int argc, char** argv) {
    if(argc < 2) {
        fprintf(stderr, "increment the content of a text file. Usage: %s filename\n", argv[0]);
        exit(1);
    }

    pthread_t threads[THREADS];
    int err;
    for(int i = 0; i < THREADS; i++) {
        err = pthread_create(threads + i, NULL, inc, argv[1]);
        if(err) {
            fprintf(stderr, "pthread_create: %s\n", strerror(err));
            exit(1);
        }
    }

    for(int i = 0; i < THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    pthread_mutex_destroy(&mtx);
    exit(0);
}